//
//  ViewController.m
//  myhuibao
//
//  Created by lijun on 13-2-4.
//  Copyright (c) 2013年 myhuibao. All rights reserved.
//
#import<QuartzCore/QuartzCore.h>
#import <MessageUI/MFMessageComposeViewController.h>
#import "ConfigViewController.h"
#import "HelpViewController.h"
#import "AboutUsViewController.h"
#import "FeedbackViewController.h"
#import "LatestViewController.h"
#import "SBJson.h"
#import "OMGToast.h"
@interface ConfigViewController ()

@end

@implementation ConfigViewController
@synthesize mainView;
@synthesize reqVersion;
- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view, typically from a nib.
    strShareApp=nil;
    mainView.layer.cornerRadius=5;
    mainView.layer.borderWidth=1;
    mainView.layer.borderColor=LINE_COLOR.CGColor;
    [[mainView layer] setShadowOffset:CGSizeMake(1, 1)];
    [[mainView layer] setShadowRadius:1];
    [[mainView layer] setShadowOpacity:1];
    [[mainView layer] setShadowColor:LINE_COLOR.CGColor];

}

- (void)viewDidUnload
{
    [self setMainView:nil];
    [super viewDidUnload];
    // Release any retained subviews of the main view.
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone) {
        return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
    } else {
        return YES;
    }
}
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.title=@"更多";
    }
    return self;
}
- (IBAction)showHelp:(id)sender {
    HelpViewController *view = [[HelpViewController alloc] initWithNibName:@"HelpViewController" bundle:nil] ;
    view.hidesBottomBarWhenPushed=YES;
    [[ self navigationController] pushViewController:view animated:YES];

}

- (IBAction)showAboutUs:(id)sender {
    AboutUsViewController *view = [[AboutUsViewController alloc] initWithNibName:@"AboutUsViewController" bundle:nil] ;
    view.hidesBottomBarWhenPushed=YES;
    [[ self navigationController] pushViewController:view animated:YES];
}

- (IBAction)showFeedback:(id)sender {
    FeedbackViewController *view = [[FeedbackViewController alloc] initWithNibName:@"FeedbackViewController" bundle:nil] ;
    view.hidesBottomBarWhenPushed=YES;
    [[ self navigationController] pushViewController:view animated:YES];
}
- (IBAction)doCheck:(id)sender {
    NSURL *url = [NSURL URLWithString:url_lastVersion];
//    isSearchFinished = false;
    reqVersion=[ASIFormDataRequest requestWithURL:url];
    [reqVersion setPostValue:@"iPhone" forKey:@"clientType"];
    [reqVersion setPostValue:curversion forKey:@"clientVersion"];
    
    [reqVersion setDidFinishSelector:@selector(finishCheck:)];
    [reqVersion setShouldAttemptPersistentConnection:NO];
    [reqVersion setDelegate: self];
    [reqVersion startAsynchronous];
}

- (IBAction)clearCache:(id)sender {
    @try {
        NSString *documentsDirectory = [NSString stringWithFormat:@"%@/Library/Caches/", NSHomeDirectory()];
        NSFileManager *fileManager = [NSFileManager defaultManager];
        NSArray *contents = [fileManager contentsOfDirectoryAtPath:documentsDirectory error:NULL];
        NSEnumerator *e = [contents objectEnumerator];
        NSString *filename;
        while ((filename = [e nextObject])) {
            
//            if ([[filename pathExtension] isEqualToString:extension]) {
            
        [fileManager removeItemAtPath:[documentsDirectory stringByAppendingPathComponent:filename] error:NULL];
//            }
        }
    }
    @catch (NSException *exception) {
        UIAlertView*alert = [[UIAlertView alloc]initWithTitle:APP_TITLE
                                                      message:exception.description
                                                     delegate:self
                                            cancelButtonTitle:@"确定"
                                            otherButtonTitles:nil];
        ((UILabel*)[[alert subviews] objectAtIndex:1]).textAlignment = UITextAlignmentLeft;
        [alert show];
    }
    @finally {
        UIAlertView*alert = [[UIAlertView alloc]initWithTitle:APP_TITLE
                                                      message:@"缓存清除成功。"
                                                     delegate:self
                                            cancelButtonTitle:@"确定"
                                            otherButtonTitles:nil];
//        ((UILabel*)[[alert subviews] objectAtIndex:1]).textAlignment = UITextAlignmentLeft;
        [alert show];
        alert = nil;
    }

}
-(void)finishCheck:(ASIHTTPRequest*) request{
    NSString *jsonStr = [request responseString];
    NSDictionary *dic = [jsonStr JSONValue];
    //NSLog(@"%@",dic);
    NSDictionary *data = [dic valueForKey:@"data"];
    if([[dic valueForKey:@"status"] isEqualToString:@"SUCCESS"])
    {
        float ver = [[data valueForKey:@"clientVersion"] floatValue];
        if(ver > [curversion floatValue]){
            downloadURL = [data valueForKey:@"downloadURL"];
            NSString *msg = [data valueForKey:@"clientDescription"];
            if ( [data valueForKey:@"clientDescription"]==[NSNull null]) {
                msg=@"";
            }
            UIAlertView*alert = [[UIAlertView alloc]initWithTitle:@""
                                                      message:msg
                                                     delegate:self
                                            cancelButtonTitle:@"取消"
                                            otherButtonTitles:@"下载",nil];
            ((UILabel*)[[alert subviews] objectAtIndex:1]).textAlignment = UITextAlignmentLeft;
            [alert show];
        }else{
            UIAlertView*alert = [[UIAlertView alloc]initWithTitle:@"提示"
                                                          message:@"您的客户端不需要更新"                                                         delegate:nil
                                                cancelButtonTitle:@"取消"
                                                otherButtonTitles:nil];
            [alert show];

        }
    }else{
        UIAlertView*alert = [[UIAlertView alloc]initWithTitle:@"提示"
                                                      message:[dic valueForKey:@"log"]                                                         delegate:nil
                                            cancelButtonTitle:@"取消"
                                            otherButtonTitles:nil];
        [alert show];
    }
}
- (void)requestFailed:(ASIHTTPRequest *)request
{
    NSError *error = [request error];
    NSLog(@"%@",error);
    if (error.code==net_failure_code) {
        [OMGToast showWithText:net_failure_msg bottomOffset:100];
    }
}

//定义的委托，buttonindex就是按下的按钮的index值
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if(buttonIndex==1){
        NSURL *url = [NSURL URLWithString:url_download];
        if (![[UIApplication sharedApplication] openURL:url])
            NSLog(@"%@%@",@"Failed to open url:",[url description]);
    }
}
- (IBAction)latest:(id)sender {
    LatestViewController *view=[[LatestViewController alloc]initWithNibName:@"LatestViewController" bundle:nil];
    view.hidesBottomBarWhenPushed=YES;
    [self.navigationController pushViewController:view animated:YES];
}

- (IBAction)doShare:(id)sender {
    if(strShareApp==nil)
    {
         NSURL *url = [NSURL URLWithString:url_shareapp];
        ASIHTTPRequest *req = [ASIHTTPRequest requestWithURL:url];
        [req startSynchronous];
        NSString *jsonStr = [req responseString];
        NSDictionary *dic = [jsonStr JSONValue];
        if ([dic objectForKey:@"data"] != [NSNull null])
        {
            strShareApp=[[NSString alloc] initWithString:[dic objectForKey:@"data"]];
        }
    }
    [self sendSMS:strShareApp recipientList:nil];
    //[req release];
}

- (void)messageComposeViewController:(MFMessageComposeViewController *)controller didFinishWithResult:(MessageComposeResult)result
{
    [self dismissModalViewControllerAnimated:YES];
    
    if (result == MessageComposeResultCancelled)
        NSLog(@"Message cancelled");
    else if (result == MessageComposeResultSent)
        NSLog(@"Message sent") ;
    else
        NSLog(@"Message failed") ;
}

- (void)sendSMS:(NSString *)bodyOfMessage recipientList:(NSArray *)recipients
{
    
    MFMessageComposeViewController *controller = [[MFMessageComposeViewController alloc] init];
    
    if([MFMessageComposeViewController canSendText])
        
    {
        controller.body = bodyOfMessage;
        
        //        controller.recipients = recipients;
        
        controller.messageComposeDelegate = self;
        //        [self.navigationController pushViewController:controller animated:YES];
        [self presentModalViewController:controller animated:YES];
    }    
}


@end
